package org.autumn.review.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "ThreadPool")
public class ThreadPool {
    // test
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(2,
                1,
                TimeUnit.SECONDS,
                10,
                (queue, task) -> {
                    // 死等
                    queue.put(task);
                    // 带有超时等待
//                    queue.offer(task, 1, TimeUnit.SECONDS);
                    // 放弃执行
                    // do nothing
                    // 调用者自己执行
//                    task.run();
                    // 抛出异常
//                    throw new RuntimeException();
                }
        );

        for (int i = 0; i < 15; i++) {
            int j = i;
            threadPool.execute(() -> {
                try {
                    TimeUnit.MINUTES.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("{}", j);
            });
        }
    }

    private BlockingQueue<Runnable> taskQueue;

    private HashSet<Worker> workers = new HashSet();

    private int coreSize;

    private long timeout;

    private TimeUnit timeUnit;

    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapacity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapacity);
        this.rejectPolicy = rejectPolicy;
    }

    public void execute(Runnable runnable) {
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(runnable);
                log.info("add worker -> {}", worker);
                workers.add(worker);
                worker.start();
            } else {
//                taskQueue.put(runnable);
                taskQueue.tryPut(rejectPolicy, runnable);
            }
        }
    }

    class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
//            while (task != null || (task = taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    log.info("running task -> {}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
                log.info("remove worker -> {}", this);
                workers.remove(this);
            }
        }
    }
}

interface RejectPolicy<T> {
    void reject(BlockingQueue<T> queue, T runnable);
}


@Slf4j(topic = "BlockingQueue")
class BlockingQueue<T> {
    private Deque<T> deque = new ArrayDeque();

    private ReentrantLock lock = new ReentrantLock();

    private Condition fullWaitSet = lock.newCondition();

    private Condition emptyWaitSet = lock.newCondition();

    private int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public T take() {
        lock.lock();
        try {
            while (deque.isEmpty()) {
                try {
                    log.info("queue is empty, waiting producer...");
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T task = deque.removeFirst();
            fullWaitSet.signal();
            log.info("take a task -> {}", task);
            return task;
        } finally {
            lock.unlock();
        }
    }

    public T poll(long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (deque.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    log.info("queue is empty, waiting producer...");
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T task = deque.removeFirst();
            fullWaitSet.signal();
            log.info("take a task -> {}", task);
            return task;
        } finally {
            lock.unlock();
        }
    }

    public void put(T t) {
        lock.lock();
        try {
            while (deque.size() == capacity) {
                try {
                    log.info("queue is full, waiting consumer...");
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.info("put task -> {}", t);
            deque.addLast(t);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    public void offer(T t, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (deque.size() == capacity) {
                try {
                    if (nanos <= 0) {
                        log.info("timeout discard task -> {}", t);
                        return;
                    }
                    log.info("queue is full, waiting consumer...");
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.info("put task -> {}", t);
            deque.addLast(t);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return deque.size();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T t) {
        lock.lock();
        try {
            while (deque.size() == capacity) {
                rejectPolicy.reject(this, t);
            }
            log.info("put task -> {}", t);
            deque.addLast(t);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }
}
